<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column label="产品名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productName`"
            :rules="formRules.productName"
            class="mb-0px!"
          >
            <el-input v-model="row.productName" placeholder="请输入产品名称" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 加批次列 -->
      <!-- <el-table-column label="批次" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productBatch`"
            class="mb-0px!"
          >
            <el-input v-model="row.productBatch" placeholder="请输入批次" disabled />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="产品单位编号" min-width="150" v-if="false">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productUnitId`"
            :rules="formRules.productUnitId"
            class="mb-0px!"
          >
            <el-input v-model="row.productUnitId" placeholder="请输入产品单位编号" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单位名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productUnitName`"
            class="mb-0px!"
          >
            <el-input v-model="row.productUnitName" placeholder="产品单位名称" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 库存数量 -->
      <el-table-column label="库存数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input v-model="row.repertoryCount" placeholder="库存数量" @change="getTotalCount" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="核销数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input v-model="row.count" placeholder="请输入产品数量" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
          <el-tooltip effect="dark" :content="row.remark" placement="top">
            <el-input v-model="row.remark" placeholder="请输入备注" disabled />
          </el-tooltip>
        </el-form-item>
      </template>
    </el-table-column>
      
      <!-- 有效期 -->
      <el-table-column label="有效期" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productValidityDate`"
            class="mb-0px!"
          >
            <el-date-picker
              v-model="row.productValidityDate"
              type="date"
              placeholder="请选择有效期"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link disabled>—</el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-form>
  <!-- <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round disabled>+ 添加ERP 核销报废管理单项</el-button>
  </el-row> -->
</template>
<script setup lang="ts">
import { CheckOutApi } from '@/api/erp/checkout'
import { SecStockApi } from '@/api/erp/secstock'
import { it } from 'node:test'

const props = defineProps<{
  outId: string | undefined // 出库编号（主表的关联字段）
  deptId: number // 部门编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  outId: [{ required: true, message: '出库编号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productUnitId: [{ required: true, message: '产品单位编号不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const productOptions = ref([])
let type : number = 91

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.outId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {

      formLoading.value = true
      formData.value = await CheckOutApi.getCheckOutItemListByOutId(val)
      // 获取产品列表
      // console.log("props.deptId:",props.deptId)
      productOptions.value = await SecStockApi.getSecStockListByDeptId(type,null,props.deptId)
 
      // 更新 formData 中的库存数量
      formData.value.forEach((item) => {
        // console.log("item:",item)
        const selectedProducts = productOptions.value.filter((product) => product.productId === item.productId);
        // console.log("selectedProducts:",selectedProducts)
        // console.log("productOptions:",productOptions.value)
        if (selectedProducts) {
          item.repertoryCount = selectedProducts.reduce((sum, product) => sum + product.count, 0);
          item.productName = selectedProducts[0].productName
          item.productUnitName = selectedProducts[0].productUnitName
        }
      })
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    outId: undefined,
    productId: undefined,
    productUnitId: undefined,
    count: undefined,
    remark: undefined,
    productBatch: undefined,
    productValidityDate: undefined,
    repertoryCount: undefined
  }
  row.outId = props.outId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })
</script>